package logic

import (
	"api/pkg"
	"context"
	"fmt"
	"strconv"
	"user_srv/user"

	"api/internal/svc"
	"api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type RealNameLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewRealNameLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RealNameLogic {
	return &RealNameLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *RealNameLogic) RealName(req *types.RealNameRequest) (resp *types.Response, err error) {
	// todo: add your logic here and delete this line
	userId := l.ctx.Value("userId").(string)
	uid, _ := strconv.Atoi(userId)
	fmt.Println(uid)
	//1,判断用户是否实名
	realName, err := l.svcCtx.UserSrv.GetUserRealName(l.ctx, &user.GetUserInfoByRealNameRequest{UserId: int64(uid)})
	if err != nil {
		return &types.Response{
			Code:    -1,
			Message: "服务器内部错误",
			Data:    nil,
		}, nil
	}
	if realName.IdCard != "" {
		return &types.Response{
			Code:    -2,
			Message: "已实名",
			Data:    nil,
		}, nil
	}
	//2,实名信息是否被使用
	idCard, err := l.svcCtx.UserSrv.GetUserRealNameByIdCard(l.ctx, &user.GetUserInfoByIdCardRequest{IdCard: req.IdCard})
	if err != nil {
		return &types.Response{
			Code:    -3,
			Message: "服务器内部错误",
			Data:    nil,
		}, nil
	}
	if idCard.UserId != 0 {
		return &types.Response{
			Code:    -4,
			Message: "该身份证已被使用",
			Data:    nil,
		}, nil
	}

	if pkg.AuthRealName(req.RealName, req.IdCard) {
		return &types.Response{
			Code:    -5,
			Message: "认证失败",
			Data:    nil,
		}, nil
	}
	//3,保存实名信息
	_, err = l.svcCtx.UserSrv.CreateUserRealName(l.ctx, &user.CreateUserRealNameRequest{
		UserId:   int64(uid),
		RealName: req.RealName,
		IdCard:   req.IdCard,
	})
	if err != nil {
		return &types.Response{
			Code:    -6,
			Message: "服务器内部错误",
			Data:    nil,
		}, nil
	}
	return &types.Response{
		Code:    0,
		Message: "ok",
		Data:    nil,
	}, nil
}
